package edu.whu.xterm.activity;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import edu.whu.xterm.R;
import edu.whu.xterm.XApplication;
import edu.whu.xterm.db.XTerm.Top10Columns;
import edu.whu.xterm.http.RequestBuilder;
import edu.whu.xterm.util.Constants;
import edu.whu.xterm.util.SharedPrefManager;
import edu.whu.xterm.widget.OnRefreshListener;
import greendroid.widget.GActionBar;
import greendroid.widget.LoaderActionBarItem;

public class Top10WforumActivity extends LoadingActivity implements
		OnRefreshListener<LoaderActionBarItem>, AdapterView.OnItemClickListener {

	private static final long INTERVAL = 1 * 60 * 60 * 1000;

	private static final String[] FROM = { Top10Columns.TITLE, Top10Columns.AUTHOR,
			Top10Columns.BOARD };

	private static final String[] PROJECTION = { Top10Columns._ID, Top10Columns.TITLE,
			Top10Columns.TOPIC_AND_RE_URL, Top10Columns.AUTHOR, Top10Columns.AUTHOR_URL,
			Top10Columns.BOARD, Top10Columns.BOARD_URL };

	private static final int[] TO = { R.id.topic_title, R.id.topic_author, R.id.topic_board };

	private GActionBar actionBar;

	LoaderActionBarItem loaderItem;

	private ListView target;

	private CursorAdapter adapter;

	private Cursor cursor;

	private SharedPrefManager sManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loading_list_view);
		actionBar = ((MainTabActivity) getParent()).getGActionBar();
		loaderItem = (LoaderActionBarItem) actionBar.getItem(MainTabActivity.ITEM_REFRESH);
		target = (ListView) findViewById(android.R.id.list);
		target.setOnItemClickListener(this);
		initLoadingView(target);

		cursor = managedQuery(Top10Columns.CONTENT_URI, PROJECTION, null, null, null);
		adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.topic_list_item,
				cursor, FROM, TO);

		XApplication app = (XApplication) getApplication();
		sManager = app.getSharedPrefManager();
		target.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		cursor.moveToPosition(position);
		String url = cursor.getString(2);
		Intent intent = new Intent(getApplicationContext(), TopicAndReplyWforumActivity.class);
		intent.putExtra(TopicAndReplyWforumActivity.KEY_URL, url);
		startActivity(intent);
	}

	private void refresh(boolean force, LoaderActionBarItem item) {
		boolean execute = false;
		if (force) {
			execute = true;
			executeLoadTask();
			return;
		}

		long time = sManager.readLong(SharedPrefManager.TOP10_LATEST_REFRESH_TIME);
		if (time < 0) {
			execute = true;
			executeLoadTask();
			return;
		}
		Time pre = new Time();
		pre.set(time);
		Time current = new Time();
		current.setToNow();
		long elapsed = current.toMillis(true) - time;
		if (elapsed > INTERVAL || (current.hour == 1 && pre.hour != 1)
				|| (current.hour == 11 && pre.hour != 11)) {
			execute = true;
			executeLoadTask();
			return;
		}
		if (!execute) {
			item.setLoading(false);
			loadSuccessed();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode != KeyEvent.KEYCODE_BACK) {
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		actionBar.setTitle(getString(R.string.tab_top10_tile));
		LoaderActionBarItem item = (LoaderActionBarItem) actionBar
				.getItem(MainTabActivity.ITEM_REFRESH);
		refresh(false, item);
	}

	@Override
	public void onRefresh(LoaderActionBarItem item) {
		refresh(false, item);
	}

	@Override
	public void executeLoadTask() {
		new Top10AsyncTask().execute();
	}

	private class Top10AsyncTask extends AsyncTask<Void, Void, Boolean> {

		private static final String TAG = "Top10AsyncTask";

		@Override
		protected void onPreExecute() {
			loaderItem.setLoading(true);
			if (adapter.isEmpty()) {
				loading();
			}
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			List<ContentValues> cvs = null;
			Document document = null;
			try {
				document = RequestBuilder.getBuilder().top10RequestWforum().call();

				Elements links = document.select("table.HotTable a[href^=wForum]");
				if (links.isEmpty()) {
					return Boolean.FALSE;
				}
				final int size = links.size();
				cvs = new ArrayList<ContentValues>(size);
				for (int i = 0; i < size;) {
					ContentValues cv = new ContentValues();
					Element board = links.get(i++);
					Element article = links.get(i++);
					Element author = links.get(i++);
					cv.put(Top10Columns.AUTHOR, author.text().trim());
					cv.put(Top10Columns.TITLE, article.text().trim());
					cv.put(Top10Columns.BOARD, board.text().trim());
					cv.put(Top10Columns.BOARD_URL, Constants.SITE + "/" + board.attr("href"));
					cv.put(Top10Columns.TOPIC_AND_RE_URL,
							Constants.SITE + "/" + article.attr("href"));
					cv.put(Top10Columns.AUTHOR_URL, Constants.SITE + "/" + author.attr("href"));
					cvs.add(cv);
				}

				if (cvs != null) {
					getContentResolver().delete(Top10Columns.CONTENT_URI, null, null);
					getContentResolver().bulkInsert(Top10Columns.CONTENT_URI,
							cvs.toArray(new ContentValues[] {}));
					sManager.writePref(SharedPrefManager.TOP10_LATEST_REFRESH_TIME,
							System.currentTimeMillis());
				}
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
				return Boolean.FALSE;
			}

			return Boolean.TRUE;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loaderItem.setLoading(false);
			if (result.booleanValue()) {
				loadSuccessed();
			} else if (adapter.isEmpty()) {
				loadFailed();
			} else {
				loadSuccessed();
			}
		}
	}
}